import 'package:html/parser.dart';
import 'package:yhdm_mobile/page/home/home_entity.dart';

class HomeParser {
  static HomeEntity parser(String html, String host) {
    var document = parse(html);
    // 解析banner
    var sliderElement = document.querySelector('#slider');
    var bannerList = List<AnimeEntity>();
    sliderElement.children.forEach((element) {
      var a = element.firstChild;
      var url = host + a.attributes['href'];
      var img = a.firstChild;
      var imageUrl = img.attributes['src'];
      var name = img.attributes['alt'];
      // print('url = $url, imageUrl = $imageUrl, name = $name');
      bannerList.add(AnimeEntity(url, imageUrl, name));
    });

    // 解析分类数据
    var classList = List<ClassEntity>();
    var list = document.querySelector('body > div.list');
    var classUrl = '';
    var className = '';
    var animeList = List<AnimeEntity>();
    list.children.forEach((element) {
      int index = list.children.indexOf(element);
      switch (index % 3) {
        case 0:
          // 分类名称和分类url
          classUrl = host + element.firstChild.attributes['href'];
          className = element.firstChild.firstChild.text;
          break;
        case 1:
          // 第一行数据
          animeList = List<AnimeEntity>();
          element.children.forEach((e) {
            var itemtext = e.getElementsByClassName('itemtext')[0];
            var url = host + itemtext.attributes['href'];
            var name = itemtext.text;
            var itemimgtext = e.getElementsByClassName('itemimgtext')[0];
            var episode = itemimgtext.text;
            var imgblock = e.getElementsByClassName('imgblock')[0];
            var style = imgblock.attributes['style'];
            var imageUrl = style.substring(
                style.indexOf("http://"), style.lastIndexOf("')"));
            var animeEntity =
                AnimeEntity(url, imageUrl, name, episode: episode);
            animeList.add(animeEntity);
          });

          break;
        case 2:
          // 第二行数据
          element.children.forEach((e) {
            var itemtext = e.getElementsByClassName('itemtext')[0];
            var url = host + itemtext.attributes['href'];
            var name = itemtext.text;
            var itemimgtext = e.getElementsByClassName('itemimgtext')[0];
            var episode = itemimgtext.text;
            var imgblock = e.getElementsByClassName('imgblock')[0];
            var style = imgblock.attributes['style'];
            var imageUrl = style.substring(
                style.indexOf("http://"), style.lastIndexOf("')"));
            var animeEntity =
                AnimeEntity(url, imageUrl, name, episode: episode);
            animeList.add(animeEntity);
          });
          classList.add(ClassEntity(className, classUrl, animeList));
          break;
      }
    });

    return HomeEntity(bannerList: bannerList, classList: classList);
  }
}
